package com.demo.controller;

import com.demo.constant.TokenConst;
import com.demo.entity.SsoResponse;
import com.demo.response.Result;
import com.demo.service.LoginUserService;
import com.demo.util.CookieUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.DeploymentException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.NoSuchAlgorithmException;

/**
 * 用户登录
 */
@Slf4j
@RestController
@RequestMapping("/login")
@Api(tags = "用户登录")
public class LoginUserController {
    @Autowired
    LoginUserService userService;
    @Autowired
    private RestTemplate restTemplate;

    @Value("${ows.sso.access-token-uri}")
    private String accessTokenUri;
    @Value("${ows.sso.verify-uri}")
    private String verifyUri;

    @GetMapping("/userLogin")
    @ApiOperation(value ="用户登录",tags={"用户登录","v20210419更新"})
    @ResponseBody
    public Result userLogin(@RequestParam(name = "userLoginName",required = true)String userLoginName,
                            @RequestParam(name = "userPass",required = true)String userPass,
                            @RequestParam(name = "workStatus",required = true)Integer workStatus) throws NoSuchAlgorithmException, DeploymentException, IOException, URISyntaxException {
        return userService.userLogin(userLoginName, userPass,workStatus);
    }

    @GetMapping("/userLoginOut")
    @ApiOperation("用户退出登录")
    @ResponseBody
    public Result userLoginOut(){
        return userService.userLoginOut();
    }

    /**
     * 登录验证（实际登录调用SSO认证服务器）
     * @date 2020-12
     * 1.第一次进来token必然为空，然后重定向到认证服务器，在认证服务器中找到了这个用户，认证服务器获取token，在此次重定向到客户端
     *   此时客户端接收到了认证服务器返回的token，再次向认证服务器发起验证的token的请求，
     */
    //@RequestMapping("/login")
    public Result login(HttpServletRequest request, HttpServletResponse response,String userLoginName,String userPass,Integer workStatus){
        log.info("登录验证回到了客户端服务器...........................");
        //当前系统登录成功之后的回调URL
        String redirectUrl = request.getParameter("redirectUrl");
        log.info("登录成功回调地址："+redirectUrl);

        //当前系统请求认证服务器成功之后返回的Token
        String token = request.getParameter("code");
        log.info("请求认证服务器之后返回的token--："+token);

        //最后重定向的URL
        String resultUrl = "redirect:";
        HttpSession session = request.getSession();

        //1. token为空【则说明当前请求不是认证服务器的回调请求，则重定向URL到认证服务器登录】
        if(StringUtils.isBlank(token)){
            //如果存在回调URL，则将这个URL添加到session
            if(StringUtils.isNoneBlank(redirectUrl)){
                session.setAttribute(TokenConst.SESSION_LOGIN_REDIRECT_URL,redirectUrl);
            }
            //拼装请求Token的地址【即认证服务器的地址】
            log.info("拼装后的地址："+resultUrl + accessTokenUri);
            resultUrl += accessTokenUri;
        }else{
            //2. token不为空【验证Token，并返回用户基本信息、所属角色、访问权限等】
            SsoResponse verifyResponse = restTemplate.getForObject(verifyUri, SsoResponse.class,token);
            log.info("验证用户成功--："+"username:"+verifyResponse.getUser_info().getUsername());

            //如果正常返回
            if(StringUtils.isNoneBlank(verifyResponse.getAccess_token())){
                //2.1 将用户信息存到session
                session.setAttribute(TokenConst.SESSION_USER,verifyResponse.getUser_info());
                //2.2 将Access Token和Refresh Token写到cookie
                CookieUtils.addCookie(response,TokenConst.COOKIE_ACCESS_TOKEN, verifyResponse.getAccess_token(),request.getServerName());
                CookieUtils.addCookie(response,TokenConst.COOKIE_REFRESH_TOKEN, verifyResponse.getRefresh_token(),request.getServerName());
            }
            //3. 从session中获取回调URL，并返回【即最开始请求的地址路径】
            redirectUrl = (String) session.getAttribute(TokenConst.SESSION_LOGIN_REDIRECT_URL);
            log.info("从session中获取到回调域地址："+redirectUrl);
//
//            session.removeAttribute("redirectUrl");
//
//            //会调域不等于空，就拼上回调域【等于空默认返回主页】
//            if(StringUtils.isNoneBlank(redirectUrl)){
//                resultUrl += redirectUrl;
//            }else{
//                log.info("回调域地址为空，将返回默认页面---首页..........");
//                resultUrl += "/user/userIndex";
//            }
        }

        log.info(resultUrl);
        //最后返回视图
        return Result.success();
    }



}
